package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.user.client.impl.UserInfoDegradeFeignClient;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

	@Autowired
	private TrackInfoMapper trackInfoMapper;
    @Autowired
    private UserInfoDegradeFeignClient userInfoDegradeFeignClient;
	@Autowired
    private VodService vodService;
	@Autowired
	private AlbumInfoMapper albumInfoMapper;
	@Autowired
	private TrackStatMapper trackStatMapper;
	@Autowired
	private AlbumInfoService albumInfoService;


	// 保存声音
	@Override
	public void saveTrackInfo(TrackInfoVo trackInfoVo, Long userId) {
		// 1.创建声音对象
		TrackInfo trackInfo = new TrackInfo();
		// 属性copy
		BeanUtils.copyProperties(trackInfoVo,trackInfo);

		// 手动设置用户id
		trackInfo.setUserId(1L);
		// 获取上一条声音
		LambdaQueryWrapper<TrackInfo> queryWrapper = new LambdaQueryWrapper<>();
		// 设置查询字段
		queryWrapper.select(TrackInfo::getOrderNum);
		// 根据专辑id查询上一条声音
		queryWrapper.eq(TrackInfo::getAlbumId, trackInfoVo.getAlbumId());
		queryWrapper.orderByDesc(TrackInfo::getId);
		queryWrapper.last(" limit 1");
		TrackInfo trackInfo_ordernum = trackInfoMapper.selectOne(queryWrapper);
		int orderNum = 1;
		if( null != trackInfo_ordernum ){
			orderNum = trackInfo_ordernum.getOrderNum() + 1;
		}
		// 最大值+1 作为下一个值
		trackInfo.setOrderNum(orderNum);

		// 声音其他信息，比如时长，大小，类型等
		// 这些信息到腾讯云查询
		// 根据声音的mediaFileId调用腾讯云方法获取
		TrackMediaInfoVo trackMediaInfoVo =
				vodService.getMediaInfoByFileId(trackInfoVo.getMediaFileId());
		// 设置到trankInfo
		trackInfo.setMediaDuration(trackMediaInfoVo.getDuration());
		trackInfo.setMediaSize(trackMediaInfoVo.getSize());
		trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
		trackInfo.setMediaType(trackMediaInfoVo.getType());
		// 调用方法添加
		trackInfoMapper.insert(trackInfo);

		// 2 操作专辑表，修改专辑里面声音数量值+1
		// 根据专辑id查询专辑原始数据
		AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfoVo.getAlbumId());
		Integer includeTrackCount = albumInfo.getIncludeTrackCount();
		// 把原始数量+1
		albumInfo.setIncludeTrackCount(includeTrackCount+1);
		// 调用方法更新
		albumInfoMapper.updateById(albumInfo);

		// 3添加声音四个统计数据，初始值0 trank_stat
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_PLAY);
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_COLLECT);
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_PRAISE);
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_COMMENT);

	}

	// 获取用户声音分页列表
	@Override
	public IPage<TrackListVo> findUserTrackPage(Page<TrackListVo> trackListVoPage, TrackInfoQuery trackInfoQuery) {
		return trackInfoMapper.selectUserTrackPage(trackListVoPage,trackInfoQuery);
	}

	// 删除声音
	@Override
	public void removeTrackInfo(Long trackId) {
		TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
		if (trackInfo == null){
			log.error("删除的声音不存在");
			return;
		}
		trackInfoMapper.deleteById(trackId);
		Long albumId = trackInfo.getAlbumId();
		AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
		Integer includeTrackCount = albumInfo.getIncludeTrackCount();
		albumInfo.setIncludeTrackCount(includeTrackCount-1);
		albumInfoMapper.updateById(albumInfo);
		LambdaQueryWrapper<TrackStat> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TrackStat::getTrackId, trackId);
		trackStatMapper.delete(queryWrapper);
		vodService.removeTrack(trackInfo.getMediaFileId());

	}

	// 修改更新声音信息
	@Override
	public void updateTrackInfo(Long trackId, TrackInfoVo trackInfoVo) {
		//1 根据trackId获取声音原始数据
		TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
		//获取原始的音频文件id fileid
		String mediaFileId_database = trackInfo.getMediaFileId();
		//设置修改值
		BeanUtils.copyProperties(trackInfoVo, trackInfo);
		//判断声音文件是否修改
		//把前端传递过来的mediaFileId 和 数据库存储的mediaFileId进行比较
		if(!trackInfoVo.getMediaFileId().equals(mediaFileId_database)) {
			//重新调用腾讯云方法，根据新的mediaFileId查询音频文件最新信息
			TrackMediaInfoVo trackMediaInfoVo =
					vodService.getMediaInfoByFileId(trackInfoVo.getMediaFileId());
			if (null==trackMediaInfoVo){
				// 抛出异常
				throw new GuiguException(ResultCodeEnum.VOD_FILE_ID_ERROR);
			}
			//最新获取音频信息设置到trackInfo
			trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
			trackInfo.setMediaType(trackMediaInfoVo.getType());
			trackInfo.setMediaDuration(trackMediaInfoVo.getDuration());
			trackInfo.setMediaSize(trackMediaInfoVo.getSize());

			//删除之前声音文件
			vodService.removeTrack(mediaFileId_database);
		}

		//调用方法修改
		trackInfoMapper.updateById(trackInfo);

	}


	/**
	 * 初始化统计数量
	 * @param trackId 声音id
	 * @param trackType 统计类型
	 */
	private void saveTrackStat(Long trackId, String trackType) {
		TrackStat trackStat = new TrackStat();
		trackStat.setTrackId(trackId);
		trackStat.setStatType(trackType);
		trackStat.setStatNum(0);
		this.trackStatMapper.insert(trackStat);
	}
}
